package com.itheima.interceptor;

import com.itheima.utill.JwtUtils;
import com.itheima.utill.CurrentHolder;
import io.jsonwebtoken.Claims;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求路径
        String url = request.getRequestURL().toString();
        if(url.contains("login")){
            //放行
            return true;
        }
        //获取请求头
        String jwt = request.getHeader("token");
        if(jwt == null || jwt.isEmpty()){
            //没有token响应401
            System.out.println("不好孩子, 我坠机了===========================");
            response.setStatus(401);
            return false;

        }
        //解析token
        try {
            Claims claims = JwtUtils.parseJWT(jwt);
            //将jwt转成int类型
            int id = Integer.parseInt(claims.get("id").toString());
            //将获取到的这个id赋值给ThreadLocal
            CurrentHolder.setCurrentId(id);
        } catch (Exception e) {
            System.out.println("传奇肘击王牢大");
            response.setStatus(401);
            return false;
        }
        //放行
        System.out.println("孩子们我又活过来了");
        return true;

    }


}
